Advertisement
Google Ad Slot: content-top
Java Collection Queue
A Queue in Java is a FIFO (First-In-First-Out) data structure that processes elements in the order they were added. It is part of the Java Collections Framework and is useful for scenarios like task scheduling, message processing, and buffering.
Implementation |
Internal Structure |
Performance |
Best Use Case |
|---|---|---|---|
LinkedList |
|
|
|
ArrayDeque |
|
|
|
Priority Queue |
|
|
|
Using PriorityQueue:
Using LinkedList as a Queue:
LinkedList are implementations of the Deque (double-ended queue) interface
Using ArrayDeque (Double-ended Queue):
ArrayDeque are implementations of the Deque (double-ended queue) interface
Queue Methods:
Basic Methods of Queue Interface
Method |
Description |
|---|---|
add(E e) |
Adds an element to the queue (throws exception if full) |
offer(E e) |
Adds an element, returns |
poll() |
Retrieves and removes the head (returns |
remove() |
Retrieves and removes the head (throws exception if empty) |
peek() |
Retrieves the head without removing it (returns |
element() |
Retrieves the head without removing it (throws exception if empty) |
Deque Methods:
All Queue Interface methods are working in Deque Interface apart from Deque have some extra methods
Method |
Description |
|---|---|
addFirst(E e) |
Adds an element on first to the queue (throws exception if full) |
addLast(E e) |
Adds an element on last to the queue (throws exception if full) |
offerFirst(E e) |
Adds an element on first, returns |
offerLast(E e) |
Adds an element on last, returns |
removeFirst() |
Retrieves and removes on first element the head (throws exception if empty) |
removeLast() |
Retrieves and removes on last element the head (throws exception if empty) |
pollFirst() |
Retrieves and removes on first element the head (returns |
pollLast() |
Retrieves and removes on last element the head (returns |
peekFirst() |
Retrieves a first element the head without removing it (returns |
peekLast() |
Retrieves a last element the head without removing it (returns |
getFirst() |
Retrieves a first element the head without removing it (throws exception if empty) |
getLast() |
Retrieves a last element the head without removing it (throws exception if empty) |